<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TenantAuth
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next)
    {
        // 检查是否已认证
        if (!Auth::guard('sanctum')->check()) {
            return response()->json([
                'success' => false,
                'message' => '未授权访问'
            ], 401);
        }

        $user = Auth::guard('sanctum')->user();

        // 检查用户是否为租户用户
        if (!$user instanceof \App\Models\TenantUser) {
            return response()->json([
                'success' => false,
                'message' => '用户类型错误'
            ], 403);
        }

        // 检查用户状态
        if ($user->status !== 'active') {
            return response()->json([
                'success' => false,
                'message' => '用户账号已被停用'
            ], 403);
        }

        // 检查租户状态
        if ($user->tenant->status !== 'active') {
            return response()->json([
                'success' => false,
                'message' => '租户账号已被停用'
            ], 403);
        }

        return $next($request);
    }
}